//
//  FMCommunityViewController.m
//  PsychologyFM
//
//  Created by zhang on 16/1/11.
//  Copyright © 2016年 ZhangLuDu. All rights reserved.
//




#import "FMPublicTopicViewController.h"
#import "FMCommentViewController.h"
#import "FMCommunityModel.h"
#import "FMCommunityTableViewCell.h"
#import "FMCommunityViewController.h"
#import "MJRefresh.h"

@interface FMCommunityViewController ()<UITableViewDelegate,UITableViewDataSource>
@property (nonatomic, strong) UIView *nagevitionBarView;
@property (nonatomic, strong) UIButton *topicButton;
@property (nonatomic, strong) UISegmentedControl *segmentControl;


@end

@implementation FMCommunityViewController

- (void)viewDidLoad {
    self.automaticallyAdjustsScrollViewInsets = YES;
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self addnagevitonBar];
    [self getInformation];
    [self addTableview];

    self.size = 10;

    self.tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        // 进入刷新状态后会自动调用这个block
        self.size += 10;
        [self getInformation];
    }];


}
#pragma mark 添加自定义导航栏
- (void)addnagevitonBar{

    self.nagevitionBarView = [[UIView alloc]initWithFrame:CGRectMake(0, 20, kScreenWidth, 44)];
    self.topicButton = [UIButton buttonWithType:(UIButtonTypeCustom)];
    self.topicButton.frame = CGRectMake(kMartin5, kMartin5, 30, 30) ;
    [self.topicButton setImage:[UIImage imageNamed:@"PostEdit@2x"] forState:(UIControlStateNormal)];
    [self.topicButton addTarget:self action:
     @selector(topicButton:) forControlEvents:(UIControlEventTouchUpInside)];
    [self.nagevitionBarView addSubview:_topicButton];
    
    NSArray *items = @[@"精华",@"最新"];
    self.segmentControl  = [[UISegmentedControl alloc]initWithItems:items];
    self.segmentControl.frame = CGRectMake((kScreenWidth - kScreenWidth / 3)/2, kMartin5, kScreenWidth/3, 30) ;
    [self.segmentControl addTarget:self action:@selector(segmentControl:) forControlEvents:(UIControlEventValueChanged)];
    [self.segmentControl setTintColor:FMOrange];
    self.segmentControl.selectedSegmentIndex = 0;
    [self.nagevitionBarView addSubview:_segmentControl];
    UIView *view = [[UIView alloc]initWithFrame:CGRectMake(0, 43, kScreenWidth, 1)];
    view.backgroundColor = FMGray;
    [self.nagevitionBarView addSubview:view];
    
    [self.view addSubview:_nagevitionBarView];
    
 

}
- (void)topicButton:(UIButton *)button{

    FMPublicTopicViewController *publicVC = [[FMPublicTopicViewController alloc]init];
    [self.navigationController pushViewController:publicVC animated:YES];

}
//segmentcontrol的点击方法
- (void)segmentControl:(UISegmentedControl *)segmentControl{

    [self getInformation];
    

}

//添加tableView
- (void)addTableview{

    self.tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 64, kScreenWidth, kScreenHeight - 64 - 49) style:(UITableViewStylePlain)];
    
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    
//注册
  [self.tableView registerClass:[FMCommunityTableViewCell class] forCellReuseIdentifier:@"MyCell"];
    
    [self.view addSubview:_tableView];
    

}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{

    if (self.segmentControl.selectedSegmentIndex == 0) {
         return self.NewArray.count;
    }else{
        return self.HotArray.count;
    }

}

#pragma mark 返回cell的高度
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    //构建字体大小的字典
    NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:[UIFont systemFontOfSize:16], NSFontAttributeName ,nil];
    FMCommunityModel *model = nil;
    if (self.segmentControl.selectedSegmentIndex == 0) {
        model = self.NewArray[indexPath.row];
    }else{
        model = self.HotArray[indexPath.row];
    }
    
    
    CGRect frame = [model.content boundingRectWithSize:CGSizeMake(kScreenWidth - 30,CGFLOAT_MAX ) options:NSStringDrawingUsesLineFragmentOrigin attributes:dic context:nil];
    NSInteger imageHeight = 0;
    
    if (model.images.count != 0) {
        imageHeight = 110;
    }
    
    if (frame.size.height < 60) {
        return 55 + frame.size.height + kScreenWidth / 8 + imageHeight ;
    }
    
    return 55 + 60 + kScreenWidth / 8  + imageHeight;
    
    
    
    
    
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{

    FMCommunityTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MyCell" forIndexPath:indexPath];
    if (self.segmentControl.selectedSegmentIndex == 1) {
        FMCommunityModel *model = self.HotArray[indexPath.row];
             cell.model = model;
    }else{
        FMCommunityModel *model = self.NewArray[indexPath.row];
        cell.model = model;
    }

    return cell;


}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{

    FMCommentViewController *commentVC = [[FMCommentViewController alloc]init];
    commentVC.rootVC = self.rootVC;
    if (self.segmentControl.selectedSegmentIndex == 0) {
        commentVC.cellModel = self.NewArray[indexPath.row];
        
    }else{
        commentVC.cellModel = self.HotArray[indexPath.row];
        
    }
    
    [self.navigationController pushViewController:commentVC animated:YES];
    

    
}


#pragma mark 请求数据
- (void)getInformation{


    NSString *str = @"http://yiapi.xinli001.com/fm/forum-thread-list.json?";
    
    NSMutableDictionary *parDic = [NSMutableDictionary dictionary];

    parDic[@"key"] = @"c0d28ec0954084b4426223366293d190";
    parDic[@"size"] = @"0";
    parDic[@"flag"] = @"0";
    
    if (self.segmentControl.selectedSegmentIndex == 0) {
    parDic[@"type"] = @"1";
    }else{
        parDic[@"type"] = @"0";

    }
    parDic[@"offset"] = [NSString stringWithFormat:@"%ld",(long)self.size];
    

    
   
    
    

    
    //    get请求 进行字符串拼接
    //    1. 先把字典的键值对以一定格式存储在数组里面
    // 初始化一个字典用来后面保存格式化的字符串键值对
    NSMutableArray *strArray = [NSMutableArray array];
    // 遍历字典
    for (NSString *key in parDic) {
        // 以key=value形式存储键值对于数组中
        NSString *str = [NSString stringWithFormat:@"%@=%@",key,parDic[key]];
        [strArray addObject:str];
    }
    //    2.将数组里面的元素 组成字符串
    NSString *arrayStr = [strArray componentsJoinedByString:@"&"];
    //    3.合成最后需要的网址
    NSString *urlStr = [str stringByAppendingString:arrayStr];
//    NSLog(@"%@",urlStr);
    
    
    
    
    
    //NSMutableDictionary *parDic = [NSMutableDictionary dictionary];
    
    [PKRequestManager requestWithUrlString:urlStr parDic:nil method:GET finish:^(NSData *data) {
        if (self.HotArray == nil) {
            self.HotArray = [NSMutableArray array];

        }
        if (self.NewArray == nil) {
            self.NewArray = [NSMutableArray array];
        }
       // self.NewArray = [NSMutableArray array];
      //  self.topicArray = [NSMutableArray array];
        
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        NSDictionary *dicData = dic[@"data"];
        if (self.segmentControl.selectedSegmentIndex == 1) {
            for (NSDictionary *oneDic in dicData) {
                FMCommunityModel *model = [[FMCommunityModel alloc]init];
                [model setValuesForKeysWithDictionary:oneDic];
                [self.HotArray addObject:model];
            }
        }else{
            for (NSDictionary *oneDic in dicData) {
                FMCommunityModel *model = [[FMCommunityModel alloc]init];
                [model setValuesForKeysWithDictionary:oneDic];
                [self.NewArray addObject:model];
            }
        
        }
        dispatch_async(dispatch_get_main_queue(), ^{
            
            [self.tableView.mj_footer endRefreshing];
           [self.tableView reloadData];
        });
    } error:^(NSError *error) {
        ;
    }];


}
- (void)viewDidDisappear:(BOOL)animated{

   // [self.nagevitionBarView removeFromSuperview];
}

- (void)viewWillAppear:(BOOL)animated{
    self.navigationController.navigationBar.hidden = YES;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
